package com.example.fantacylib


import android.graphics.Bitmap
import android.media.FaceDetector
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.TextureView
import android.view.View
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import com.bumptech.glide.Glide
import com.example.baseutils.BitmapUtil
import com.example.baseutils.FileUtil
import com.example.baseutils.showToast
import com.example.baseutils.start
import com.example.baseutils.ui.ProgressDialog
import com.example.cameralib.CameraLibActivity
import com.example.fantacylib.databinding.ActivityCaptureBinding
import com.example.fantacylib.ui.ConfirmDialog
import com.example.net.http.FantacyRetrofitCreator
import com.example.net.oss.UpFileToOss
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class CaptureActivity : CameraLibActivity() {
    private val TAG = "CaptureActivity"
    private lateinit var binding: ActivityCaptureBinding
    private var mCount = 7
    private var countTime = mCount
    private val mAutoOutTime = 15
    private var countDownTimer: CountDownTimer? = null
    private var autoOutTimer: CountDownTimer? = null
    private var progressDialog: ProgressDialog? = null
    private var price = ""
    private var oderId = 0
    private val upLoadScope = CoroutineScope(Dispatchers.IO)
    private val confirmDialog:ConfirmDialog by lazy {
        ConfirmDialog(this).init(false)
    }
    companion object {
        const val COUNT_TIME = "COUNT_TIME"
        const val PRICE_KEY = "PRICE_KEY"
        const val MERGE_LIST = "MERGE_LIST"
        const val ORDER_ID = "ORDER_ID"
        var localPath = ""
    }

    override fun takeBitmap(bitmap: Bitmap) {
        Log.i(TAG, "takeBitmap: ")
        runOnUiThread {
            //展示图片结果
            autoOutTimer()
            Glide.with(binding.ivCaptureResult).load(bitmap).into(binding.ivCaptureResult)
            binding.ivCaptureResult.visibility=View.VISIBLE
            confirmDialog.showConfirm(object:ConfirmDialog.IConfirmCallBack{
                override fun onConfirm() {
                    uploadImg(bitmap)
                }
                override fun onCancel() {
                    countTime()
                }
            })
        }
    }
    private fun uploadImg(bitmap: Bitmap){
        autoOutTimer?.cancel()
        //开启dialog提示
        binding.clAnim.visibility=View.VISIBLE
        //存储本地
        upLoadScope.launch {
            localPath = FileUtil.getPicPath("fantacy")
            Log.i(TAG, "localPath: $localPath")
            BitmapUtil.save2jpg(bitmap, localPath)
            val upFileToOss = UpFileToOss(this@CaptureActivity, localPath, 5)
            var upState = -1
            while (upState == -1 || upState == -2) {
                upState = upFileToOss.execute()
                if (upState != 0) {
                    delay(1000)
                    Log.e(TAG, "上传照片失败，准备重试")
                }
            }
            Log.i(TAG, "upState: $upState")
            val mergeResult =
                FantacyRetrofitCreator.pushPhoto(FantacyMain.spuId, upFileToOss.objectKey)
            //请求接口进行结果返回，或超时退出
            withContext(Dispatchers.Main) {
                if (mergeResult?.mergePic.isNullOrEmpty()) upState = -1
                if (upState != 0) {
                    Log.e(TAG, "图片失败: ")
                    "上传图片失败，请联系工作人员".showToast(this@CaptureActivity)
                    autoOutTimer()
                    return@withContext
                }
                stopPreview()
                oderId = mergeResult?.orderId ?: 0
                //如果成功就进入付款页
                PayActivity().start(this@CaptureActivity) {
                    putExtra(PRICE_KEY, price)
                    putExtra(ORDER_ID, oderId)
                    putStringArrayListExtra(MERGE_LIST, mergeResult!!.mergePic)
                }
            }
        }
    }

    override fun getCameraShowView(): TextureView {
        return findViewById(R.id.textureView)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_capture)
        binding.btnCapture.setOnClickListener {
            countTime()
        }
        binding.btnBack.setOnClickListener { finish() }
        countTime = intent.getIntExtra(COUNT_TIME, 10)
        mCount = countTime
        binding.btnBackHome.text = "$mCount 秒 返回主页"
        price = intent.getStringExtra(PRICE_KEY) ?: "未获取到"
        binding.btnBackHome.setOnLongClickListener {
            photoRotate()
            "图片已旋转，请测试查看".showToast(this@CaptureActivity)
            return@setOnLongClickListener true
        }
       AnimationUtils.loadAnimation(this,R.anim.circle_rotate).let {binding.ivCircleAnim.startAnimation(it) }


    }

    override fun onStart() {
        super.onStart()
        startPreview()
        //开始超时计时
        autoOutTimer()
        openFace(true)
    }

    private fun countTime() {
        binding.btnCapture.isEnabled = false
        binding.tvCount.visibility = View.VISIBLE
        binding.ivCaptureResult.visibility=View.GONE
        countDownTimer?.cancel()
        autoOutTimer?.cancel()
        countDownTimer = object : CountDownTimer(mCount * 1000L, 1000L) {
            override fun onTick(p0: Long) {
                mCount -= 1
                binding.tvCount.text = "$mCount"
                binding.tvNotifyTime.text = "倒计时:$mCount S"
            }

            override fun onFinish() {
                cancelCapture()
                takeFastPhoto()
            }

        }.start()
    }

    private fun autoOutTimer(force: Boolean = false) {
        autoOutTimer?.cancel()
        autoOutTimer = object : CountDownTimer(mAutoOutTime * 1000L, 1000L) {
            override fun onTick(p0: Long) {}
            override fun onFinish() {
                if (force) {
                    finish()
                    return
                }
                AlertDialog.Builder(this@CaptureActivity)
                    .setTitle("超时退出提示")
                    .setMessage("即将在 $mAutoOutTime 秒后自动退出到主页面！")
                    .setNegativeButton("稍等一会儿") { dialog, which ->
                        //重复超时计时
                        autoOutTimer()
                    }
                    .setPositiveButton("退出吧") { dialog, which ->
                        dialog.dismiss()
                        finish()
                    }.show()
                autoOutTimer(true)
            }
        }.start()
    }

    private fun cancelCapture() {
        binding.btnCapture.isEnabled = true
        mCount = countTime
        binding.tvNotifyTime.text = "倒计时:$mCount S"
        binding.tvCount.visibility = View.GONE
        binding.ivCaptureResult.visibility=View.GONE
    }

    override fun onStop() {
        super.onStop()
        Log.i(TAG, "onStop: ")
        countDownTimer?.cancel()
        autoOutTimer?.cancel()
        cancelCapture()
    }

    override fun face(mFace: Array<out FaceDetector.Face>?, bitmap: Bitmap?) {
        super.face(mFace, bitmap)
        if (mFace?.size==null) {
            return
        }
        Log.i(TAG, "face: ${mFace.size}")
        //检测到人脸，拍照
        if( binding.tvCount.visibility == View.VISIBLE)
            return
        openFace(false)
        runOnUiThread {
            countTime()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "onDestroy: ")
        upLoadScope.cancel()
    }
}